<template>
  <div class="page-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">客户管理</h1>
      <p class="page-description">查看和管理所有客户信息</p>
    </div>
    
    <!-- 筛选器 -->
    <a-card class="filter-card" :bordered="false">
      <div class="filter-container">
        <a-form :model="filters" @submit="handleSearch" class="filter-form" :label-col-style="{ width: '80px', flexShrink: 0 }">
          <!-- 第一行 -->
          <div class="filter-row">
            <a-form-item label="客户姓名" class="filter-item">
              <a-input
                v-model="filters.search"
                placeholder="搜索客户姓名"
                allow-clear
                style="width: 180px"
              />
            </a-form-item>
            
            <a-form-item label="电话号码" class="filter-item">
              <a-input
                v-model="filters.phone"
                placeholder="搜索电话号码"
                allow-clear
                style="width: 180px"
              />
            </a-form-item>
            
            <a-form-item class="button-group">
              <a-space :size="8">
                <a-button type="primary" html-type="submit" :loading="guestStore.loading">
                  <template #icon>
                    <icon-search />
                  </template>
                  搜索
                </a-button>
                <a-button @click="handleReset">
                  <template #icon>
                    <icon-refresh />
                  </template>
                  重置
                </a-button>
              </a-space>
            </a-form-item>
          </div>
          
          <!-- 第二行 -->
          <div class="filter-row">
            <a-form-item label="会员等级" class="filter-item">
              <a-select
                v-model="filters.vip_level"
                placeholder="选择会员等级"
                allow-clear
                style="width: 180px"
              >
                <a-option
                  v-for="option in guestStore.vipLevelOptions"
                  :key="option.value"
                  :value="option.value"
                >
                  {{ option.label }}
                </a-option>
              </a-select>
            </a-form-item>
          </div>
        </a-form>
        
        <div class="action-buttons">
          <a-space :size="12">
            <a-button type="primary" @click="handleAddGuest">
              <template #icon>
                <icon-plus />
              </template>
              添加客户
            </a-button>
            <a-button @click="handleExport">
              <template #icon>
                <icon-download />
              </template>
              导出数据
            </a-button>
          </a-space>
        </div>
      </div>
    </a-card>
    
    <!-- 客户列表 -->
    <a-card class="table-card" :bordered="false">
      <a-table
        :columns="columns"
        :data="guestStore.guests"
        :loading="guestStore.loading"
        :pagination="paginationConfig"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #vipLevel="{ record }">
          <a-tag :color="getVipLevelColor(record.vip_level)">
            {{ getVipLevelText(record.vip_level) }}
          </a-tag>
        </template>
        
        <template #totalSpent="{ record }">
          ¥{{ record.total_spent?.toLocaleString() || 0 }}
        </template>
        
        <template #actions="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="handleViewGuest(record)">
              <template #icon>
                <icon-eye />
              </template>
              查看
            </a-button>
            <a-button type="text" size="small" @click="handleEditGuest(record)">
              <template #icon>
                <icon-edit />
              </template>
              编辑
            </a-button>
            <a-popconfirm
              content="确定要删除这个客户吗？"
              @ok="handleDeleteGuest(record.id)"
            >
              <a-button type="text" size="small" status="danger">
                <template #icon>
                  <icon-delete />
                </template>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>
    
    <!-- 客户表单模态框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      :width="600"
      :ok-text="modalMode === 'view' ? '关闭' : '确定'"
      :hide-cancel="modalMode === 'view'"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="姓名" field="name">
              <a-input 
                v-model="formData.name" 
                placeholder="请输入姓名"
                :disabled="modalMode === 'view'"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="电话号码" field="phone">
              <a-input 
                v-model="formData.phone" 
                placeholder="请输入电话号码"
                :disabled="modalMode === 'view'"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="邮箱" field="email">
              <a-input 
                v-model="formData.email" 
                placeholder="请输入邮箱"
                :disabled="modalMode === 'view'"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="身份证号" field="id_number">
              <a-input 
                v-model="formData.id_number" 
                placeholder="请输入身份证号"
                :disabled="modalMode === 'view'"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="会员等级" field="vip_level">
              <a-select
                v-model="formData.vip_level"
                placeholder="请选择会员等级"
                :disabled="modalMode === 'view'"
                style="width: 100%"
              >
                <a-option
                  v-for="option in guestStore.vipLevelOptions"
                  :key="option.value"
                  :value="option.value"
                >
                  {{ option.label }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="性别" field="gender">
              <a-radio-group 
                v-model="formData.gender"
                :disabled="modalMode === 'view'"
              >
                <a-radio value="male">男</a-radio>
                <a-radio value="female">女</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="地址" field="address">
          <a-textarea
            v-model="formData.address"
            placeholder="请输入地址"
            :rows="2"
            :disabled="modalMode === 'view'"
          />
        </a-form-item>
        
        <a-form-item label="备注" field="notes">
          <a-textarea
            v-model="formData.notes"
            placeholder="请输入备注"
            :rows="2"
            :disabled="modalMode === 'view'"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { useGuestStore } from '@/stores/guest'
import {
  IconPlus,
  IconSearch,
  IconRefresh,
  IconEye,
  IconEdit,
  IconDelete,
  IconDownload
} from '@arco-design/web-vue/es/icon'

const guestStore = useGuestStore()

// 筛选条件
const filters = reactive({
  search: '',
  phone: '',
  vip_level: ''
})

// 模态框状态
const modalVisible = ref(false)
const modalTitle = ref('')
const modalMode = ref('add') // add | edit | view
const currentGuestId = ref(null)

// 表单引用
const formRef = ref()

// 表单数据
const formData = reactive({
  name: '',
  phone: '',
  email: '',
  id_number: '',
  vip_level: 0,
  gender: 'male',
  address: '',
  notes: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入姓名' }
  ],
  phone: [
    { required: true, message: '请输入电话号码' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址' }
  ]
}

// 表格列配置
const columns = [
  { title: '姓名', dataIndex: 'name', width: 120 },
  { title: '电话号码', dataIndex: 'phone', width: 140 },
  { title: '邮箱', dataIndex: 'email', width: 180 },
  { title: '身份证号', dataIndex: 'id_number', width: 180 },
  { title: '会员等级', slotName: 'vipLevel', width: 120 },
  { title: '消费总额', slotName: 'totalSpent', width: 120 },
  { title: '操作', slotName: 'actions', width: 180, fixed: 'right' }
]

// 分页配置
const paginationConfig = computed(() => ({
  current: guestStore.pagination.current,
  pageSize: guestStore.pagination.size,
  total: guestStore.pagination.total,
  showTotal: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 50, 100]
}))

// 获取会员等级颜色
const getVipLevelColor = (level) => {
  const colors = {
    0: 'gray',    // 白银会员
    1: 'orange',  // 黄金会员
    2: 'blue',    // 白金会员
    3: 'purple'   // 钻石会员
  }
  return colors[level] || 'gray'
}

// 获取会员等级文本
const getVipLevelText = (level) => {
  const texts = {
    0: '白银会员',
    1: '黄金会员',
    2: '白金会员',
    3: '钻石会员'
  }
  return texts[level] || '未知'
}

// 处理搜索
const handleSearch = () => {
  guestStore.setFilters(filters)
  guestStore.fetchGuests()
}

// 处理重置
const handleReset = () => {
  guestStore.resetFilters()
  Object.assign(filters, {
    search: '',
    phone: '',
    vip_level: ''
  })
  guestStore.fetchGuests()
}

// 处理导出数据
const handleExport = () => {
  try {
    const exportData = guestStore.guests.map(guest => ({
      '姓名': guest.name,
      '电话号码': guest.phone,
      '邮箱': guest.email || '-',
      '身份证号': guest.id_number || '-',
      '会员等级': getVipLevelText(guest.vip_level),
      '性别': guest.gender === 'male' ? '男' : '女',
      '地址': guest.address || '-',
      '总消费(元)': guest.total_spent || 0,
      '备注': guest.notes || '-'
    }))

    const headers = Object.keys(exportData[0])
    const csvContent = [
      headers.join(','),
      ...exportData.map(row => headers.map(header => {
        const value = row[header]
        if (typeof value === 'string' && (value.includes(',') || value.includes('\n'))) {
          return `"${value.replace(/"/g, '""')}"`
        }
        return value
      }).join(','))
    ].join('\n')

    const BOM = '\uFEFF'
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' })
    
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `客户数据_${new Date().toLocaleDateString()}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    Message.success('导出成功！')
  } catch (error) {
    console.error('导出失败:', error)
    Message.error('导出失败，请重试')
  }
}

// 处理分页变化
const handlePageChange = (page) => {
  guestStore.setPagination({ current: page })
  guestStore.fetchGuests()
}

// 处理页面大小变化
const handlePageSizeChange = (pageSize) => {
  guestStore.setPagination({ current: 1, size: pageSize })
  guestStore.fetchGuests()
}

// 处理添加客户
const handleAddGuest = () => {
  modalMode.value = 'add'
  modalTitle.value = '添加客户'
  resetForm()
  modalVisible.value = true
}

// 处理查看客户
const handleViewGuest = (record) => {
  modalMode.value = 'view'
  modalTitle.value = '客户详情'
  fillForm(record)
  modalVisible.value = true
}

// 处理编辑客户
const handleEditGuest = (record) => {
  modalMode.value = 'edit'
  modalTitle.value = '编辑客户'
  currentGuestId.value = record.id
  fillForm(record)
  modalVisible.value = true
}

// 处理删除客户
const handleDeleteGuest = async (id) => {
  await guestStore.deleteGuestData(id)
}

// 处理模态框确认
const handleModalOk = async () => {
  if (modalMode.value === 'view') {
    modalVisible.value = false
    return
  }
  
  const valid = await formRef.value.validate()
  if (!valid) return
  
  let success = false
  if (modalMode.value === 'add') {
    success = await guestStore.createGuestData(formData)
  } else if (modalMode.value === 'edit') {
    success = await guestStore.updateGuestData(currentGuestId.value, formData)
  }
  
  if (success) {
    modalVisible.value = false
  }
}

// 处理模态框取消
const handleModalCancel = () => {
  modalVisible.value = false
}

// 填充表单
const fillForm = (record) => {
  Object.assign(formData, {
    name: record.name || '',
    phone: record.phone || '',
    email: record.email || '',
    id_number: record.id_number || '',
    vip_level: record.vip_level || 0,
    gender: record.gender || 'male',
    address: record.address || '',
    notes: record.notes || ''
  })
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    phone: '',
    email: '',
    id_number: '',
    vip_level: 0,
    gender: 'male',
    address: '',
    notes: ''
  })
  formRef.value?.resetFields()
}

// 组件挂载时获取数据
onMounted(() => {
  guestStore.fetchGuests()
})
</script>

<style scoped lang="scss">
.filter-card {
  margin-bottom: 12px;
  
  :deep(.arco-card-body) {
    padding: 12px 16px;
  }
}

.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 12px;
  
  @media (max-width: 1024px) {
    flex-direction: column;
    gap: 8px;
  }
}

.filter-form {
  flex: 1;
  min-width: 0;
}

.filter-row {
  display: grid;
  grid-template-columns: 240px 240px auto;
  gap: 8px 12px;
  align-items: center;
  margin-bottom: 8px;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  @media (max-width: 1200px) {
    grid-template-columns: 240px 240px;
  }
  
  @media (max-width: 768px) {
    grid-template-columns: 1fr;
    gap: 8px;
  }
}

.filter-item {
  display: flex;
  align-items: center;
  
  :deep(.arco-form-item) {
    margin-bottom: 0;
    width: 100%;
    display: flex;
    align-items: center;
  }
  
  :deep(.arco-form-item-label-col) {
    width: 70px;
    flex: 0 0 70px;
    padding-right: 6px;
  }
  
  :deep(.arco-form-item-label) {
    font-weight: 500;
    color: #1d2129;
    white-space: nowrap;
    text-align: right;
    width: 100%;
    font-size: 13px;
  }
  
  :deep(.arco-form-item-wrapper-col) {
    flex: 1;
    min-width: 0;
  }
  
  :deep(.arco-input-wrapper),
  :deep(.arco-select-view),
  :deep(.arco-picker) {
    width: 100%;
    max-width: 160px;
    min-width: 160px;
  }
}

.button-group {
  grid-column: 3;
  grid-row: 1;
  display: flex;
  justify-content: flex-end;
  
  :deep(.arco-form-item) {
    margin-bottom: 0;
  }
  
  @media (max-width: 1200px) {
    grid-column: 1 / -1;
    grid-row: auto;
    margin-top: 4px;
    justify-content: flex-end;
  }
  
  @media (max-width: 768px) {
    width: 100%;
    
    :deep(.arco-space) {
      width: 100%;
      display: flex;
      
      .arco-btn {
        flex: 1;
      }
    }
  }
}

.action-buttons {
  flex-shrink: 0;
  
  @media (max-width: 1024px) {
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
  
  @media (max-width: 768px) {
    :deep(.arco-space) {
      width: 100%;
      display: flex;
      
      .arco-btn {
        flex: 1;
      }
    }
  }
}

.table-card {
  margin-bottom: 16px;
}
</style>
